///////////////////////////////////////////////////////////////////////////////
// Global function Part.
#include "Stdafx.h"
#include "Global.h"
#include "MacroGetSetData.h"

int _GetVarString(int iMax, TCHAR* tBuf, TCHAR* sBuf, int& index, char* strFn, int nLine)
{
	int nLen = GetByte(sBuf, index);
	if(nLen >= iMax || nLen < 0) return 0; 

	_GetString(tBuf, sBuf, nLen, index, strFn, nLine);
	*(tBuf + nLen) = 0;

	return nLen;
}

int _GetVarLongString(int iMax, TCHAR* tBuf, TCHAR* sBuf, int& index, char* strFn, int nLine)
{
	int nLen = GetShort(sBuf, index);
	if(nLen >= iMax || nLen < 0) return 0; 

	_GetString(tBuf, sBuf, nLen, index, strFn, nLine);
	*(tBuf + nLen) = 0;

	return nLen;
}

void _GetString(char* tBuf, char* sBuf, int len, int& index, char* strFn, int nLine)
{
	char tempStr[512];
	memset(tempStr, 0, sizeof(tempStr));
	wsprintf(tempStr, "File = %s, Line = %d", strFn, nLine);

	memcpy(tBuf, sBuf+index, len);
	index += len;
}

void _DisplayErrorMsg(SQLHANDLE hstmt, LPCTSTR strFile, int nLine)
{
	SQLCHAR			SqlState[256], Msg[1024];
	SQLINTEGER		NativeError;
	SQLSMALLINT		i, MsgLen;
	SQLRETURN		rc2;

	i = 1;
	while ((rc2 = SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, i, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA)
	{
		if(MsgLen > 256) Msg[256] = '\0';
		TRACE("***[ %s, %d ] %s, %d, %s, %d ***\n", strFile, nLine, SqlState,NativeError,Msg,MsgLen);

		i++;
	}
}

int myrand( int min, int max, BOOL bSame )
{
/*
	static int nOld = 0;
	int nRet = 0;
	int nLoop = 10;

	if( min == max ) return min;

	while(nLoop--)
	{
		nRet =  (rand() % (max-min+1)) + min;
		if(bSame == FALSE)
		{
			if(nRet != nOld) 
			{
				nOld = nRet;
				return nRet;
			}
		}
		else return nRet;
	}

	return nRet;
*/
	if( min == max ) return min;
	if( min > max )
	{
		int temp = min;
		min = max;
		max = temp;
	}

//	if( min < 0 || max < 0 )
//	{
//		return myminusrand( min, max );
//	}

	double gap = max - min + 1;
	double rrr = (double)RAND_MAX / gap;

	double rand_result;

	rand_result = (double)rand() / rrr;

	if( (int)( min + (int)rand_result ) < min ) return min;
	if( (int)( min + (int)rand_result ) > max ) return max;

	return (int)( min + (int)rand_result );
}
